package com.ali.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * BIO
 */
public class BIOMain {
    public static void main(String[] args) {
        try {
            //构建监听服务并绑定监听端口
            ServerSocket serverSocket = new ServerSocket(8080);
            while (true) {
                System.out.println("等待客户端连接");
                //获取客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("接收客户端连接");
                handle(socket);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理客户端连接
     */
    private static void handle(Socket socket) throws IOException {
        byte[] bytes = new byte[1];
        int length;
        //获取输入流
        try (InputStream inputStream = socket.getInputStream()) {
            while (true) {
                //写入内容至缓冲区
                length = inputStream.read(bytes);
                if (length > 0) {
                    System.out.println("接收内容：" + new String(bytes, 0, length));
                } else if (length == -1) {
                    System.out.println("客户端断开连接");
                    break;
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }
}
